#
# MainWindow.py
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from StatusWidget import *
from LibraryView import *
from SourceView import *
from ArtworkView import *
from PlaylistWindow import *
from SearchWidget import *
from DB.Library import *
from PrefsDialog import *
from RadioView import *
from AudioCDView import *
###GTD:: from PodTrackView import *
from Slimp3View import *
from CD.CDROM import *
from PixmapPushButton import *
from MultiPushButton import *
from ShuttleWidget import *
from VolumeWidget import *
from SpeedWidget import *
from FunctionWidget import *
from MainLibraryView import *
from PlaylistView import *
from TrashView import *
from RemotePlaylistView import *
#from MusicCDMounter import *
from Player import *
from CD.Ripper import *
#from MusicPodManager import *
from Utils.Paths import *
from BurnerSettingsDialog import *
from EqualizerWindow import *
from StationsView import *
from EncoderView import *
from Utils.Settings import *
from Utils.Summary import *
from Utils.utils import *
from UpperWidget import UpperWidget
import time
	
class MainWindow(KMainWindow):
	def __init__(self,version,app):
		KMainWindow.__init__(self)
		self.app = app
		self.libraryViewRef = None

		# placeholders for orphan KHTML views
		self.browserView = None
		self.browserViewIcecast = None
		self.slimp3View = None
		self.musicstoreView  = None
		self.settings = Settings.settings()
		#print self.settings
		self.visualizerSize = 'large'
		self.visualizerFullscreen = False
		self.initActions()
		self.initMenus()
		self.initView()
		self.initSignals()
		self.hasBurner = CDROMS.singleton().canBurn()
		self._version = version
		self.setIcon(QPixmap(art("8trak_64.png")))
		self.musicPlayer = Player.singleton()
		self.musicRipper = Ripper.singleton()
		CDROMS.singleton().startTimer()
		CDLibraries.singleton()
		if Settings.settings().get('isMP3Beamer'):
			self.showMinimized()
	
	def version(self):
		return self._version

	def initActions(self):
		self.initFileActions()
		self.initEditActions()
		self.initControlsActions()
		#self.initVisualizerActions()
		self.initAdvancedActions()

	def initFileActions(self):
		#GTD:: Winamp style keybindings	
		self.showSearchAction = KAction(i18n("&Play"),KShortcut(Qt.CTRL+Qt.Key_X),self.slotPlay,self.actionCollection(),"PlayWinAmp")
		self.showSearchAction = KAction(i18n("&Pause"),KShortcut(Qt.CTRL+Qt.Key_C),self.slotPause,self.actionCollection(),"PauseWinAmp")
		self.showSearchAction = KAction(i18n("&Prev"),KShortcut(Qt.CTRL+Qt.Key_Z),self.slotPreviousSong,self.actionCollection(),"PrevWinAmp")
		self.showSearchAction = KAction(i18n("&Stop"),KShortcut(Qt.CTRL+Qt.Key_V),self.slotStop,self.actionCollection(),"StopWinAmp")
		self.showSearchAction = KAction(i18n("&Next"),KShortcut(Qt.CTRL+Qt.Key_B),self.slotNextSong,self.actionCollection(),"NextWinAmp")
		
		self.showSearchAction = KAction(i18n("&ShowSearch"),KShortcut(Qt.CTRL+Qt.Key_F),self.slotShowSearch,self.actionCollection(),"Show Search")
		self.showSearchAction2 = KAction(i18n("&ShowSearchC"),KShortcut(Qt.Key_Slash),self.slotShowSearch,self.actionCollection(),"Show SearchSlash")
		self.showSearchActionHide = KAction(i18n("&HideSearch"),KShortcut(Qt.Key_Escape),self.slotHideSearch,self.actionCollection(),"Hide Search")
		
		



		self.newPlaylistAction = KAction(i18n("&New Playlist"),KShortcut(Qt.CTRL+Qt.Key_N),self.slotNewPlaylist,self.actionCollection(),"newPlaylist")
		self.newPlaylistAction.setWhatsThis(i18n("Create a new, empty, untitled playlist"))
		self.newPlaylistFromSelectionAction = KAction(i18n("New &Playlist From Selection"),KShortcut(Qt.SHIFT+Qt.CTRL+Qt.Key_N),self.slotNewPlaylistFromSelection,self.actionCollection(),"newPlaylistFromSelection")
		self.newPlaylistFromSelectionAction.setWhatsThis(i18n("Create a new playlist containing the selected songs"))
		self.newSmartPlaylistAction = KAction(i18n("New &Smart Playlist"),KShortcut(Qt.ALT+Qt.CTRL+Qt.Key_N),self.slotNewSmartPlaylist,self.actionCollection(),"newSmartPlaylist")
		self.newSmartPlaylistAction.setWhatsThis(i18n("Create a new smart playlist"))
		self.addToLibraryAction = KAction(i18n("&Add File to Media Library..."),KShortcut(Qt.CTRL+Qt.Key_O),self.slotAddToLibrary,self.actionCollection(),"addToLibrary")
		self.addToLibraryAction.setWhatsThis(i18n("Presents a dialog to choose a music file to be added to the Media Library"))
		self.addDirectoryToLibraryAction = KAction(i18n("Add &Folder to Media Library..."),KShortcut(Qt.SHIFT+Qt.CTRL+Qt.Key_O),self.slotAddDirectoryToLibrary,self.actionCollection(),"addDirectoryToLibrary")
		self.addDirectoryToLibraryAction.setWhatsThis(i18n("Presents a dialog to choose a directory containing music files to be added to the Media Library"))
		self.addStreamAction = KAction(i18n("Add &Station"),KShortcut(Qt.CTRL+Qt.Key_S),self.slotAddStream,self.actionCollection(),"addStream")
		self.addStreamAction.setWhatsThis(i18n("Presents a dialog to set information to create a station"))
		self.importAction = KAction(i18n("I&mport..."),KShortcut(Qt.SHIFT+Qt.CTRL+Qt.Key_O),self.slotImport,self.actionCollection(),"import")
		self.importAction.setWhatsThis(i18n("Not Implemented"))
		self.exportSongListAction = KAction(i18n("&Export Song List..."),KShortcut.null(),self.slotExportSongList,self.actionCollection(),"exportSongList")
		self.exportSongListAction.setWhatsThis(i18n("Presents a dialog to select a file in which to store XML about the selected playlist"))
		self.exportLibraryAction = KAction(i18n("Export &Library..."),KShortcut.null(),self.slotExportLibrary,self.actionCollection(),"exportLibrary")
		self.exportLibraryAction.setWhatsThis(i18n("Presents a dialog to select a file in which to store XML about the Media Library"))
		self.getInfoAction = KAction(i18n("Get &Info..."),KShortcut(Qt.CTRL+Qt.Key_I),self.slotGetInfo,self.actionCollection(),"getInfo")
		self.getInfoAction.setWhatsThis(i18n("Presents a dialog to view and edit information about the selected songs"))
		self.editSmartPlaylistAction = KAction(i18n("&Edit Smart Playlist"),KShortcut.null(),self.slotEditSmartPlaylist,self.actionCollection(),"editSmartPlaylist")
		self.editSmartPlaylistAction.setWhatsThis(i18n("Edit the settings for the selected smart playlist"))
		self.showSongFileAction = KAction(i18n("Show Song &File"),KShortcut(Qt.CTRL+Qt.Key_R),self.slotShowSongFile,self.actionCollection(),"showSongFile")
		self.showSongFileAction.setWhatsThis(i18n("Opens a file window to directory containing the selected song's file"))
		self.showCurrentSongAction = KAction(i18n("Show &Current Song"),KShortcut(Qt.CTRL+Qt.Key_L),self.slotShowCurrentSong,self.actionCollection(),"showCurrentSong")
		self.showCurrentSongAction.setWhatsThis(i18n("Shows the playlist item for the currently playing song"))
		self.burnPlaylistToDiscAction = KAction(i18n("&Burn Playlist to Disc"),KShortcut.null(),self.slotBurnPlaylistToDisc,self.actionCollection(),"burnPlaylistToDisc")
		self.burnPlaylistToDiscAction.setWhatsThis(i18n("Writes a CD containing the enabled songs in the current playlist"))
		#self.syncWithDeviceAction = KAction(i18n("S&ync with Dell DJ"),KShortcut.null(),self.slotSyncWithDevice,self.actionCollection(),"sync")
		#self.syncWithDeviceAction.setWhatsThis(i18n("Synchronizes the contens of the Dell Digital Jukebox with the Media Library"))
		self.preferencesAction = KAction(i18n("&Preferences..."),KShortcut.null(),self.slotPreferences,self.actionCollection(),"preferences")
		self.preferencesAction.setWhatsThis(i18n("Presents a dialog to changes various settings for 8traK"))
		self.validateAction = KAction(i18n("Validate Media Library"),KShortcut.null(),self.slotValidate,self.actionCollection(),"validate")
		self.validateAction.setWhatsThis(i18n("Checks the integrity of the Media Library database"))
		self.findDuplicatesAction = KAction(i18n("Find Duplicates"),KShortcut.null(),self.slotFindDuplicates,self.actionCollection(),"findDuplicates")
		self.findDuplicatesAction.setWhatsThis(i18n("Creates a playlist containing possible duplicate tracks"))
		self.findUntaggedAction = KAction(i18n("Find non-Tagged Tracks"),KShortcut.null(),self.slotFindUntagged,self.actionCollection(),"findNonTagged")
		self.findUntaggedAction.setWhatsThis(i18n("Creates a playlist containing tracks with no artist or album name"))
		self.quitAction = KStdAction.quit(self.slotQuit,self.actionCollection())
		self.quitAction.setWhatsThis(i18n("Saves any changes and quits 8traK"))

	def initEditActions(self):
		self.undoAction = KStdAction.undo(self.slotUndo,self.actionCollection())
		self.redoAction = KStdAction.redo(self.slotRedo,self.actionCollection())
		self.cutAction = KStdAction.cut(self.slotCut,self.actionCollection())
		self.copyAction = KStdAction.copy(self.slotCopy,self.actionCollection())
		self.pasteAction = KStdAction.paste(self.slotPaste,self.actionCollection())
		self.clearAction = KAction(i18n("&Clear"),KShortcut(Qt.Key_Delete),self.slotClear,self.actionCollection(),"clear")
		self.selectAllAction = KAction(i18n("Select &All"),KShortcut(Qt.CTRL+Qt.Key_A),self.slotSelectAll,self.actionCollection(),"selectAll")
		self.selectNoneAction = KAction(i18n("Select &None"),KShortcut(Qt.SHIFT+Qt.CTRL+Qt.Key_A),self.slotSelectNone,self.actionCollection(),"selectNone")
		self.emptyTrashAction = KAction(i18n("Empty &Trash"),KShortcut.null(),self.slotEmptyTrash,self.actionCollection(),"emptytrash")
		self.toggleBrowserAction = KAction(i18n("Show &Browser"),KShortcut(Qt.CTRL+Qt.Key_B),self.slotToggleBrowser,self.actionCollection(),"showBrowser")
		self.toggleArtworkAction = KAction(i18n("Show Art&work"),KShortcut(Qt.CTRL+Qt.Key_G),self.slotToggleArtwork,self.actionCollection(),"showArtwork")
		self.viewOptionsAction = KAction(i18n("View &Options"),KShortcut(Qt.CTRL+Qt.Key_J),self.slotViewOptions,self.actionCollection(),"viewOptions")

	def initControlsActions(self):
		self.playAction = KAction(i18n("&Play"),KShortcut(Qt.Key_Space),self.slotPlay,self.actionCollection(),"play")
		self.pauseAction = KAction(i18n("&Pause"),KShortcut.null(),self.slotPause,self.actionCollection(),"pause")
		self.nextSongAction = KAction(i18n("&Next Song"),KShortcut(Qt.CTRL+Qt.Key_Right),self.slotNextSong,self.actionCollection(),"nextSong")
		self.previousSongAction = KAction(i18n("Pre&vious Song"),KShortcut(Qt.CTRL+Qt.Key_Left),self.slotPreviousSong,self.actionCollection(),"previousSong")
		self.toggleShuffleAction = KToggleAction(i18n("&Shuffle"),KShortcut.null(),self.slotToggleShuffle,self.actionCollection(),"shuffle")
		self.repeatOffAction = KRadioAction(i18n("Repeat &Off"),KShortcut.null(),self.slotRepeatOff,self.actionCollection(),"repeatOff")
		self.repeatAllAction = KRadioAction(i18n("Repeat &All"),KShortcut.null(),self.slotRepeatAll,self.actionCollection(),"repeatAll")
		self.repeatOneAction = KRadioAction(i18n("Repeat On&e"),KShortcut.null(),self.slotRepeatOne,self.actionCollection(),"repeatOne")
		self.repeatOffAction.setExclusiveGroup("repeat")
		self.repeatAllAction.setExclusiveGroup("repeat")
		self.repeatOneAction.setExclusiveGroup("repeat")
		self.volumeUpAction = KAction(i18n("Volume &Up"),KShortcut(Qt.CTRL+Qt.Key_Up),self.slotVolumeUp,self.actionCollection(),"volumeUp")
		self.volumeDownAction = KAction(i18n("Volume &Down"),KShortcut(Qt.CTRL+Qt.Key_Down),self.slotVolumeDown,self.actionCollection(),"volumeDown")
		self.muteAction = KToggleAction(i18n("&Mute"),KShortcut(Qt.ALT+Qt.CTRL+Qt.Key_Down),self.slotMute,self.actionCollection(),"mute")
		#ejectIconSet = QIconSet(QPixmap(art("buttoneject.png")))
		self.ejectDiscAction = KAction(i18n("&Eject Disc"),KShortcut(Qt.CTRL+Qt.Key_E),self.slotEjectDisc,self.actionCollection(),"ejectDisc")

	def initVisualizerActions(self):
		self.toggleVisualizerAction = KAction(i18n("Turn &Visualizer On"),KShortcut(Qt.CTRL+Qt.Key_T),self.slotToggleVisualizer,self.actionCollection(),"visualizer")
		self.smallVisualizerAction = KToggleAction(i18n("&Small"),KShortcut.null(),self.slotSmallVisualizer,self.actionCollection(),"smallVisualizer")
		self.mediumVisualizerAction = KToggleAction(i18n("&Medium"),KShortcut.null(),self.slotMediumVisualizer,self.actionCollection(),"mediumVisualizer")
		self.largeVisualizerAction = KToggleAction(i18n("&Large"),KShortcut.null(),self.slotLargeVisualizer,self.actionCollection(),"largeVisualizer")
		self.smallVisualizerAction.setExclusiveGroup("visualizerSize")
		self.mediumVisualizerAction.setExclusiveGroup("visualizerSize")
		self.largeVisualizerAction.setExclusiveGroup("visualizerSize")
		self.fullscreenVisualizerAction = KToggleAction(i18n("&Full Screen"),KShortcut(Qt.CTRL+Qt.Key_F),self.slotFullScreenVisualizer,self.actionCollection(),"fullScreenVisualizer")

	def initAdvancedActions(self):
		self.openStreamAction = KAction(i18n("Open &Stream..."),KShortcut(Qt.CTRL+Qt.Key_U),self.slotOpenStream,self.actionCollection(),"openStream")
		self.convertSelectionAction = KAction(i18n("&Convert Selection to MP3..."),KShortcut.null(),self.slotConvertSelection,self.actionCollection(),"convertSelection")
		self.consolidateLibraryAction = KAction(i18n("Consolidate &Library..."),KShortcut.null(),self.slotConsolidateLibrary,self.actionCollection(),"consolidateLibrary")
		self.getTrackNamesAction = KAction(i18n("&Get CD Track Names"),KShortcut.null(),self.slotGetTrackNames,self.actionCollection(),"getTrackNames")
		self.submitTrackNamesAction = KAction(i18n("&Submit CD Track Names"),KShortcut.null(),self.slotSubmitTrackNames,self.actionCollection(),"submitTrackNames")
		self.joinTracksAction = KAction(i18n("&Join CD Tracks"),KShortcut.null(),self.slotJoinTracks,self.actionCollection(),"joinTracks")
		self.convertTagsAction = KAction(i18n("Convert &ID3 Tags"),KShortcut.null(),self.slotConvertTags,self.actionCollection(),"convertTags")

	def initMenus(self):
		self.initFileMenu()
		#self.initEditMenu()
		#self.initControlsMenu()
		#self.initVisualizerMenu()
		#self.initAdvancedMenu()
		self.initHelpMenu()
		#self.menuBar()#.hide()

	def initFileMenu(self):
		self.fileMenu = QPopupMenu();
		self.newPlaylistAction.plug(self.fileMenu)
		self.newPlaylistFromSelectionAction.plug(self.fileMenu)
		#self.newSmartPlaylistAction.plug(self.fileMenu)
		self.addToLibraryAction.plug(self.fileMenu)
		self.addDirectoryToLibraryAction.plug(self.fileMenu)
		self.addStreamAction.plug(self.fileMenu)
		self.fileMenu.insertSeparator()
		#self.importAction.plug(self.fileMenu)
		self.exportSongListAction.plug(self.fileMenu)
		self.exportLibraryAction.plug(self.fileMenu)
		self.fileMenu.insertSeparator()
		self.getInfoAction.plug(self.fileMenu)
		#self.editSmartPlaylistAction.plug(self.fileMenu)
		self.showSongFileAction.plug(self.fileMenu)
		self.showCurrentSongAction.plug(self.fileMenu)
		self.fileMenu.insertSeparator()
		self.burnPlaylistToDiscAction.plug(self.fileMenu)
		#self.syncWithDeviceAction.plug(self.fileMenu)
		self.fileMenu.insertSeparator()
		self.validateAction.plug(self.fileMenu)
		self.findDuplicatesAction.plug(self.fileMenu)
		self.findUntaggedAction.plug(self.fileMenu)
		self.fileMenu.insertSeparator()
		self.quitAction.plug(self.fileMenu)
		self.menuBar().insertItem(i18n("&File"),self.fileMenu)

	def initEditMenu(self):
		self.editMenu = QPopupMenu()
		self.undoAction.plug(self.editMenu)
		self.redoAction.plug(self.editMenu)
		self.editMenu.insertSeparator()
		self.cutAction.plug(self.editMenu)
		self.copyAction.plug(self.editMenu)
		self.pasteAction.plug(self.editMenu)
		self.clearAction.plug(self.editMenu)
		self.editMenu.insertSeparator()
		self.selectAllAction.plug(self.editMenu)
		self.selectNoneAction.plug(self.editMenu)
		self.editMenu.insertSeparator()
		self.emptyTrashAction.plug(self.editMenu)
		self.editMenu.insertSeparator()
		self.toggleBrowserAction.plug(self.editMenu)
		self.toggleArtworkAction.plug(self.editMenu)
		self.editMenu.insertSeparator()
		self.preferencesAction.plug(self.editMenu)
		self.menuBar().insertItem(i18n("&Edit"),self.editMenu)

	def initControlsMenu(self):
		self.controlsMenu = QPopupMenu()
		self.playAction.plug(self.controlsMenu)
		self.controlsMenu.insertSeparator()
		self.nextSongAction.plug(self.controlsMenu)
		self.previousSongAction.plug(self.controlsMenu)
		self.toggleShuffleAction.plug(self.controlsMenu)
		self.controlsMenu.insertSeparator()
		self.repeatOffAction.plug(self.controlsMenu)
		self.repeatAllAction.plug(self.controlsMenu)
		self.repeatOneAction.plug(self.controlsMenu)
		self.controlsMenu.insertSeparator()
		self.volumeUpAction.plug(self.controlsMenu)
		self.volumeDownAction.plug(self.controlsMenu)
		self.muteAction.plug(self.controlsMenu)
		self.controlsMenu.insertSeparator()
		self.ejectDiscAction.plug(self.controlsMenu)
		self.menuBar().insertItem(i18n("&Controls"),self.controlsMenu)

	def initVisualizerMenu(self):
		self.visualizerMenu = QPopupMenu()
		self.toggleVisualizerAction.plug(self.visualizerMenu)
		self.visualizerMenu.insertSeparator()
		self.smallVisualizerAction.plug(self.visualizerMenu)
		self.mediumVisualizerAction.plug(self.visualizerMenu)
		self.largeVisualizerAction.plug(self.visualizerMenu)
		self.visualizerMenu.insertSeparator()
		self.fullscreenVisualizerAction.plug(self.visualizerMenu)
		self.menuBar().insertItem(i18n("&Visualizer"),self.visualizerMenu)

	def initAdvancedMenu(self):
		self.advancedMenu = QPopupMenu()
		self.openStreamAction.plug(self.advancedMenu)
		self.advancedMenu.insertSeparator()
		self.convertSelectionAction.plug(self.advancedMenu)
		self.advancedMenu.insertSeparator()
		self.consolidateLibraryAction.plug(self.advancedMenu)
		self.advancedMenu.insertSeparator()
		self.getTrackNamesAction.plug(self.advancedMenu)
		self.submitTrackNamesAction.plug(self.advancedMenu)
		self.advancedMenu.insertSeparator()
		self.joinTracksAction.plug(self.advancedMenu)
		self.advancedMenu.insertSeparator()
		self.convertTagsAction.plug(self.advancedMenu)
		self.menuBar().insertItem(i18n("&Advanced"),self.advancedMenu)

	def initHelpMenu(self):
		self.menuBar().insertItem(i18n("&Help"),self.helpMenu(""))
		
	def updateMenusAndControls(self):
		selection = self.trackView.selectedTrackIDs()
		hasSelection = len(selection)>0
		singleSelection = len(selection)==1
		self.updateFileMenu(selection,hasSelection,singleSelection)
		self.updateEditMenu(selection,hasSelection,singleSelection)
		self.updateControlsMenu()
		#self.updateVisualizerMenu()
		self.updateAdvancedMenu()
	
	def updateFileMenu(self,selection,hasSelection,singleSelection):
		self.newPlaylistFromSelectionAction.setEnabled(hasSelection)
		self.newSmartPlaylistAction.setEnabled(False) # XXX DSM pending implementation
		self.addStreamAction.setEnabled(self.trackView.canStream())
		self.importAction.setEnabled(False) # XXX DSM pending implementation
		self.editSmartPlaylistAction.setEnabled(False) # XXX DSM pending implementation
		self.getInfoAction.setEnabled(hasSelection and self.trackView.canGetInfo())
		(track,library,playlist) = Player.getCurrentTrackInfo()
##		if track:
##			print "current track stream",track.isStream,"status",track.playStatus
##		else:
##			print "no track"
		showCurrent = track!=None and not track.isStream and track.playStatus!='idle'
		self.showCurrentSongAction.setEnabled(showCurrent)
		self.showSongFileAction.setEnabled(singleSelection and self.trackView.canShowLocation())
		self.burnPlaylistToDiscAction.setEnabled(self.trackView.canBurn() and self.hasBurner)
		#self.syncWithDeviceAction.setEnabled(DellNJB.singleton().hasDDJ())
		#self.exportSongListAction.setEnabled(self.trackView.canExport())
	
	def updateEditMenu(self,selection,hasSelection,singleSelection):	
		self.undoAction.setEnabled(False)
		self.cutAction.setEnabled(False)
		self.copyAction.setEnabled(False)
		self.clearAction.setEnabled(hasSelection and self.trackView.canDelete())
		self.selectAllAction.setEnabled(True)
		self.selectNoneAction.setEnabled(hasSelection)
		trash = Library.mainLibrary().playlistWithName('Trash')
		self.emptyTrashAction.setEnabled(trash.hasTracks())
		canBrowse = self.trackView.canBrowse()
		self.toggleBrowserAction.setEnabled(self.trackView.canBrowse())
		#if canBrowse:
			#if self.trackView.browserShowing():
		#		self.toggleBrowserAction.setText(i18n("Hide &Browser"))
		#	else:
		#		self.toggleBrowserAction.setText(i18n("Show &Browser"))
		#if self.artworkShowing():
		#	self.toggleArtworkAction.setText(i18n("Hide Art&work"))
		#	try: self.showArtworkButton.setState('on')
		#	except: pass
		#else:
		#	self.toggleArtworkAction.setText(i18n("Show Art&work"))
		#	try: self.showArtworkButton.setState('off')
		#	except: pass
		#f (self.artwork.getArtCap()):
		#	self.toggleArtworkAction.setEnabled(True)
		#	self.showArtworkButton.setEnabled(True)
		#else :
		#	self.toggleArtworkAction.setEnabled(False)
		#	self.showArtworkButton.setEnabled(False)
		#	self.artworkView.hide()
	
		

	def updateControlsMenu(self):	
		self.toggleShuffleAction.setChecked(self.settings.get('Shuffle'))
		try:
			if self.musicPlayer.shuffle:
				self.shuffleButton.setState('on')
			else:
				self.shuffleButton.setState('off')
		except: pass
		self.repeatOffAction.setChecked(self.settings.get('Repeat')=='off')
		self.repeatAllAction.setChecked(self.settings.get('Repeat')=='all')
		self.repeatOneAction.setChecked(self.settings.get('Repeat')=='one')
		try: self.repeatButton.setState(self.musicPlayer.repeat)
		except: pass
		self.ejectDiscAction.setEnabled(self.trackView.canEject())
	'''
	def updateVisualizerMenu(self):	
		if self.visualizerShowing():
			self.toggleVisualizerAction.setText(i18n('Turn Visualizer Off'))
			try: self.visualizerButton.setState('on')
			except: pass
		else:
			self.toggleVisualizerAction.setText(i18n('Turn Visualizer On'))
			try:
				if self.visualizerFullscreen:
					self.visualizerButton.setState('full')
				else:
					self.visualizerButton.setState('off')
			except: pass
		self.smallVisualizerAction.setChecked(self.visualizerSize=='small')
		self.mediumVisualizerAction.setChecked(self.visualizerSize=='medium')
		self.largeVisualizerAction.setChecked(self.visualizerSize=='large')
		self.fullscreenVisualizerAction.setChecked(self.visualizerFullscreen)
	'''
	def updateAdvancedMenu(self): # XXX DSM disable all for now
		self.openStreamAction.setEnabled(False)
		self.convertSelectionAction.setEnabled(False)
		self.consolidateLibraryAction.setEnabled(False)
		self.getTrackNamesAction.setEnabled(False)
		self.submitTrackNamesAction.setEnabled(False)
		self.joinTracksAction.setEnabled(False)
		self.convertTagsAction.setEnabled(False)

	def slotNewPlaylist(self):
		library = Library.mainLibrary()
		library.addNewPlaylist()
	
	def slotShowSearch(self): 
		if not self.search.isVisible(): 
			self.search.show()
			self.search.setFocus()

	def slotHideSearch(self): 
		if self.search.isVisible(): 
			self.search.hide() 
			self.search.clearText()
			self.setFocus()

	def slotNewPlaylistFromSelection(self):
		library = Library.mainLibrary()
		trackIDs = self.trackView.selectedTrackIDs()
		name = library.uniquePlaylistNameFromTracks(library.tracksWithTrackIDs(trackIDs))
		playlist = library.addNewPlaylist(name)
		playlist.addTrackIDs(trackIDs)
		#self.copySelectionToPlaylist(playlist)

	def copySelectionToPlaylist(self,playlist):
		self.trackView.copySelectionToPlaylist(playlist)

	def slotNewSmartPlaylist(self):
		self.notImplemented("New Smart Playlist")

	def slotAddToLibrary(self):
		library = Library.mainLibrary()
		lastAddDirectory = self.settings.get('Last Add Directory',os.path.expanduser('~/Music/'))
		try: fileNames = KFileDialog.getOpenFileNames(library.fileFilter(),lastAddDirectory,self,"open dialog",i18n("Select Music Files"))
		except: fileNames = KFileDialog.getOpenFileNames(lastAddDirectory,library.fileFilter(),self,i18n("Select Music Files"))
		if fileNames and len(fileNames)>0:
			(lastAddDirectory,dummy) = os.path.split(unikode(fileNames[0]).encode('latin-1'))
			self.settings['Last Add Directory'] = lastAddDirectory
			files = []
			for file in fileNames:
				files.append(unikode(file).encode('latin-1'))
			library.importFiles(files)

	def slotAddDirectoryToLibrary(self):
		library = Library.mainLibrary()
		lastAddDirectory = self.settings.get('Last Add Directory',os.path.expanduser('~/Music/'))
		try: fileName = KFileDialog.getExistingDirectory(lastAddDirectory, self, None, i18n("Select Music Directory"))
		except: fileName = KFileDialog.getExistingDirectory(lastAddDirectory,self,i18n("Select Music Directory"))
		if fileName:
			self.settings['Last Add Directory'] = unikode(fileName)
			library.importFiles([unikode(fileName).encode('latin-1')])
	
	def slotAddStream(self):
		self.trackView.addStream()

	def slotImport(self):
		self.notImplemented("Import")

	def slotExportSongList(self):
		self.trackView.playlist.exportSongList()

	def slotExportLibrary(self):
		Library.mainLibrary().playlistWithName("Library").exportSongList()

	def slotGetInfo(self):
		trackIDs = self.trackView.selectedTrackIDs()
		if len(trackIDs)==1:
			self.getInfo(trackIDs[0])
		else:
			self.getMultiInfo(trackIDs)
	
	def getInfo(self,trackID):
		lib = self.trackView.library
		lib.trackWithTrackID(trackID).getInfo()
		lib.markDirty()

	def getMultiInfo(self,trackIDs):
		self.trackView.getMultiInfoForTrackIDs(trackIDs)

	def slotEditSmartPlaylist(self):
		self.notImplemented("Edit Smart Playlist")

	def slotShowSongFile(self):
		trackIDs = self.trackView.selectedTrackIDs()
		lib = self.trackView.library
		tracks = lib.tracksWithTrackIDs(trackIDs)
		if len(tracks)>0:
			tracks[0].showLocation()

	def slotShowCurrentSong(self):
		(track,library,playlist) = Player.getCurrentTrackInfo()
		#print track,library,playlist
		if track and self.sources:
			if self.sources.showSongSource(track,library,playlist):
				self.trackView.showSongItemForTrack(track)

	def slotBurnPlaylistToDisc(self):
		self.trackView.playlist.burnPlaylistToDisc()
	
	def slotPreferences(self):
		prefs = PrefsDialog()
		ret = prefs.exec_loop()
		if ret==QDialog.Accepted:
			prefs.unload()

	def slotValidate(self):
		Library.mainLibrary().validate()

	def slotFindDuplicates(self):
		Library.mainLibrary().findDuplicates()
	
	def slotFindUntagged(self):
		Library.mainLibrary().findUntagged()

	def slotQuit(self):
		#ArtworkWindow.closeAll()
		PlaylistWindow.closeAll()
		self.close()
		self.app.saveStuff()
		self.app.quit()

	def closeEvent(self,e):
		sizes = self.listViews.sizes()
		self.settings['Main Window Split'] = str(sizes)
		sizes = [self.x(),self.y(),self.width(),self.height()]
		self.settings['Main Window Position'] = str(sizes)
		#PlaylistWindow.closeAll()
		#KMainWindow.closeEvent(self,e)
		self.hide()
		e.ignore()

	def slotUndo(self):
		self.notImplemented("Undo")

	def slotRedo(self):
		self.notImplemented("Redo")

	def slotCut(self):
		self.notImplemented("Cut")

	def slotCopy(self):
		self.notImplemented("Copy")

	def slotPaste(self):
		self.notImplemented("Paste")

	def slotClear(self):
		if self.trackView.canDelete():
			self.trackView.removeSelectedItems()
		#self.notImplemented("Clear")

	def slotSelectAll(self):
		self.trackView.selectAll(True)

	def slotSelectNone(self):
		self.trackView.selectAll(False)

	def slotEmptyTrash(self):
		result = QMessageBox.information( self, i18n("Empty Trash"),\
			i18n("Are you sure you want to remove the items in the Trash permanently?"),\
			i18n("&OK"), i18n("&Cancel"), "", 0,1 )
		if result==0:
			Library.mainLibrary().emptyTrash()

	def slotToggleBrowser(self):
		if self.browserShowing():
			self.hideBrowser()
		else:
			self.showBrowser()

	def browserShowing(self):
		return self.trackView.browserShowing()
		
	def showBrowser(self):
		self.trackView.showBrowser()
		self.updateMenusAndControls()

	def hideBrowser(self):
		self.trackView.hideBrowser()
		self.updateMenusAndControls()
	
	def slotToggleArtwork(self):
		if self.artworkShowing():
			self.hideArtwork()
		else:
			self.showArtwork()

	def artworkShowing(self):
		return self.artworkView.isVisible()
		
	def showArtwork(self):
		self.artwork.fetchItemArtwork()
		self.artworkView.show()
		self.artworkView.setAcceptDrops(True)
		self.updateMenusAndControls()
		
	def hideArtwork(self):
		self.artworkView.hide()
		self.updateMenusAndControls()
	
	def disableArt(self):
		self.artwork.putArtCap(False)
		self.hideArtwork()
		
	def slotViewOptions(self):
		self.notImplemented("View Options")

	def slotPlay(self):
		status = Player.status()
		#print "slotPlay",status
		if status==None or Player.shouldPlay():
			#print "attempt to play"
			if self.trackView:
				#print "got trackview"
				if self.trackView.canPlay():
					#print "can play"
					self.trackView.play()
		elif status['isPlaying']:
			Player.pause()
		else:
			Player.play()

	def slotPause(self):
		Player.pause()

	def slotStop(self):
		self.notImplemented("Stop")

	def slotRewind(self):
		self.notImplemented("Rewind")

	def slotFastForward(self):
		self.notImplemented("Fast Forward")

	def slotNextSong(self):
		Player.nextTrack()

	def slotPreviousSong(self):
		Player.prevTrack()

	def slotToggleShuffle(self):
		if self.musicPlayer.shuffle:
			self.slotShuffleOff()
		else:
			self.slotShuffleOn()

	def slotShuffleOff(self):
		self.musicPlayer.shuffle = False
		self.updateMenusAndControls()

	def slotShuffleOn(self):
		self.musicPlayer.shuffle = True
		self.updateMenusAndControls()

	def slotRepeatOff(self):
		self.musicPlayer.repeat = 'off'
		self.updateMenusAndControls()

	def slotRepeatAll(self):
		self.musicPlayer.repeat = 'all'
		self.updateMenusAndControls()

	def slotRepeatOne(self):
		self.musicPlayer.repeat = 'one'
		self.updateMenusAndControls()

	def slotVolumeUp(self):
		self.musicPlayer.increaseVolume()

	def slotVolumeDown(self):
		self.musicPlayer.decreaseVolume()

	def slotMute(self):
		self.notImplemented("Mute")

	def slotEjectDisc(self):
		if self.trackView.canEject():
			Ripper.killCurrentRipper()
			Player.killCurrentPlayerIfCD()
			if self.trackView.eject():
				if self.trackViewType=='audiocd':
					self.selectLibrary()
	'''
	def slotToggleVisualizer(self):
		self.toggleVisualizer()
	def toggleVisualizer(self):
		if self.visualizerShowing():
			self.hideVisualizer()
		else:
			self.showVisualizer()
	
	def hideVisualizer(self):
		self.listsOrVisualizer.raiseWidget(self.listViews)
		self.updateMenusAndControls()

	def showVisualizer(self):
		self.listsOrVisualizer.raiseWidget(self.visualizer)
		self.updateMenusAndControls()
		
	def visualizerShowing(self):
		try: return self.listsOrVisualizer.visibleWidget()==self.visualizer
		except: return False

	def slotSmallVisualizer(self):
		self.visualizerSize = 'small'
		self.updateMenusAndControls()
	
	def slotMediumVisualizer(self):
		self.visualizerSize = 'medium'
		self.updateMenusAndControls()

	def slotLargeVisualizer(self):
		self.visualizerSize = 'large'
		self.updateMenusAndControls()

	def slotFullScreenVisualizer(self):
		self.visualizerFullscreen = not self.visualizerFullscreen
		self.updateMenusAndControls()
	'''

	def slotOpenStream(self):
		self.notImplemented("Open Stream")

	def slotConvertSelection(self):
		self.notImplemented("Convert Selection")

	def slotConsolidateLibrary(self):
		self.notImplemented("Consolidate Library")

	def slotGetTrackNames(self):
		self.notImplemented("Get Tracks")

	def slotSubmitTrackNames(self):
		self.notImplemented("Submit Tracks")

	def slotJoinTracks(self):
		self.notImplemented("Join Tracks")

	def slotConvertTags(self):
		self.notImplemented("Convert Tags")

	def slotEqualizer(self):
		#self.notImplemented("Equalizer")
		EqualizerWindow.toggleEqualizer()

	def slotRIP(self):
		if self.trackView.canImport():
			self.trackView.doImport()
		#self.notImplemented("Import")
	
	def slotSync(self):
		if self.trackView.canSync():
			self.trackView.sync()
	
	def slotRefresh(self):
		pass
		#RadioLibrary.singleton().fetch()
		#self.notImplemented("Refresh")
	
	def slotOptions(self):
		self.notImplemented("Options")

	def slotBurnEnable(self):
		self.notImplemented("Burn Enabled")
	
	def slotBurn(self):
		self.notImplemented("Burn")

	def about(self):
		QMessageBox.about( self, \
		i18n("About 8traK"),i18n(\
		"8traK Media Player ")+self.version()+\
		'''\n\nLead Developers: 2006 - Georgi Damyanov & Jule Slootbeek'''
		'''\n\nThanks to the developers of:\n\n'''
		'''python, PyQt, Xine, LAME, Ogg Vorbis,\n'''
		'''cdrecord, cdparanoia, mpg321, id3lib, libnjb,\n'''
		'''pyxine, and pyid3lib'''
		)

	def notImplemented(self,item):
		KMessageBox.error(self,"%s not implemented" % item,"Not Implemented")

	def initView(self):
		self.top = QWidget(self)
		self.setCentralWidget(self.top)
		#self.setCentralWidget(None)
		layout = QVBoxLayout(self.top)
		layout.setMargin(2)
		self.layout().addWidget(self.top)
		layout.setSpacing(2)
		
		self.buildUpperBar(self.top,layout)
		self.buildMain(self.top,layout)

		self.buildLowerBar(self.top,layout)
		self.top.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)	
		# XXX DSM from settings
		self.selectLibrary()

	def buildUpperBar(self,containerTop,containerLayout):
		self.backColor=QColor(Settings.settings().get('ColorR'),Settings.settings().get('ColorG'),Settings.settings().get('ColorB'))
		
		self.upperBar=UpperWidget(containerTop,containerLayout)

		containerLayout.addWidget(self.upperBar)
		
		layout =self.upperBar.getLayout()
		container=self.upperBar.getContainer()
		container.setPaletteBackgroundColor(self.backColor)

		layout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		self.buildShuttleControls(container,layout)
		self.buildVolumeControls(container,layout)
		
		layout.addItem(QSpacerItem(20,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		self.buildStatusView(container,layout)
		
		rlayout=QVBoxLayout(container)
		layout.addLayout(rlayout)
		
		rdlayout=QHBoxLayout(container)
		rlayout.addItem(QSpacerItem(1,20,QSizePolicy.Fixed,QSizePolicy.Fixed))
		rlayout.addLayout(rdlayout)
		
		self.buildRandShuffle(container,rdlayout)
		rdlayout.addItem(QSpacerItem(10,1,QSizePolicy.Fixed,QSizePolicy.Fixed))
		self.buildFunctionButton(container,rdlayout)
		rdlayout.addItem(QSpacerItem(10,1,QSizePolicy.Fixed,QSizePolicy.Fixed))

		#
		# shuttle controls
		##
	def buildShuttleControls(self,container,containerLayout):
		self.shuttleControls = ShuttleWidget(container)
		containerLayout.addWidget(self.shuttleControls)
		QObject.connect(self.shuttleControls,PYSIGNAL('play'),self.slotPlay)
		QObject.connect(self.shuttleControls,PYSIGNAL('pause'),self.slotPause)
		QObject.connect(self.shuttleControls,PYSIGNAL('prevTrack'),self.slotPreviousSong)
		QObject.connect(self.shuttleControls,PYSIGNAL('nextTrack'),self.slotNextSong)
	
		#
		# volume slider
		#
	def buildVolumeControls(self,container,containerLayout):
		self.volumeControl = VolumeWidget(container)
		containerLayout.addWidget(self.volumeControl)
		QWhatsThis.add(self.volumeControl,i18n("This slider controls the volume of the music."))
	
		#
		# status view
		#
	def buildStatusView(self,container,containerLayout):
		self.status = StatusWidget(container)
		self.status.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed)
		containerLayout.addWidget(self.status,40)
		QWhatsThis.add(self.status,i18n("This view shows the progress of actions that 8traK is performing."))

		#
		# search controls
		#
	def buildSearch(self,container,containerLayout):
		self.search = SearchWidget(container)
		containerLayout.addWidget(self.search)
		self.search.hide();

		#
		# function button
		#
	def buildFunctionButton(self,container,containerLayout):
		self.functionButton = FunctionWidget(container)
		
		containerLayout.addWidget(self.functionButton)
		QObject.connect(self.functionButton,PYSIGNAL('browse'),self.slotToggleBrowser)
		QObject.connect(self.functionButton,PYSIGNAL('import'),self.slotRIP)
		QObject.connect(self.functionButton,PYSIGNAL('refresh'),self.slotRefresh)
		QObject.connect(self.functionButton,PYSIGNAL('options'),self.slotOptions)
		QObject.connect(self.functionButton,PYSIGNAL('burnEnable'),self.slotBurnEnable)
		QObject.connect(self.functionButton,PYSIGNAL('burn'),self.slotBurnPlaylistToDisc)
		QObject.connect(self.functionButton,PYSIGNAL('sync'),self.slotSync)
		
	def buildRandShuffle(self,container,containerLayout):
		randShuffleButtons = QHBoxLayout()
		containerLayout.addLayout(randShuffleButtons)
		randShuffleButtons.setSpacing(2)
		bSize = QSize(28,22)
		#backColor=QColor(Settings.settings().get('ColorR'),Settings.settings().get('ColorG'),Settings.settings().get('ColorB'))

		#
		# shuffle button
		#
		iconoff = QIconSet(QPixmap(art("buttonshuffleoff.png")))
		iconon = QIconSet(QPixmap(art("buttonshuffleon.png")))
		self.shuffleButton = MultiPushButton("",container)
		self.shuffleButton.setFixedSize(bSize)
		self.shuffleButton.addState('off',iconoff,PYSIGNAL('slotShuffleOn'),'on')
		self.shuffleButton.addState('on',iconon,PYSIGNAL('slotShuffleOff'),'off')
		self.shuffleButton.setPaletteBackgroundColor(self.backColor)
		randShuffleButtons.addWidget(self.shuffleButton)
		QObject.connect(self.shuffleButton,PYSIGNAL("slotShuffleOn"),self.slotShuffleOn)
		QObject.connect(self.shuffleButton,PYSIGNAL("slotShuffleOff"),self.slotShuffleOff)
		QToolTip.add(self.shuffleButton,i18n("Turn shuffle on or off"))
		# XXX DSM from settings
		self.shuffleButton.setState('off')
		self.shuffleButton.setFlat(True)
		QWhatsThis.add(self.shuffleButton,i18n("This button changes the shuffle behavior of the player. You can also use the <b>Shuffle</b> command from the <b>Controls</b> menu."))

		#
		# repeat button
		#
		iconoff = QIconSet(QPixmap(art("buttonrepeatoff.png")))
		iconone = QIconSet(QPixmap(art("buttonrepeatone.png")))
		iconall = QIconSet(QPixmap(art("buttonrepeatall.png")))
		self.repeatButton = MultiPushButton("",container)	
		self.repeatButton.setFixedSize(bSize)
		self.repeatButton.addState('off',iconoff,PYSIGNAL('repeatAll'))
		self.repeatButton.addState('all',iconall,PYSIGNAL('repeatOne'))
		self.repeatButton.addState('one',iconone,PYSIGNAL('repeatOff'))
		self.repeatButton.setPaletteBackgroundColor(self.backColor)
		
		randShuffleButtons.addWidget(self.repeatButton)
		QObject.connect(self.repeatButton,PYSIGNAL('repeatOff'),self.slotRepeatOff)
		QObject.connect(self.repeatButton,PYSIGNAL('repeatAll'),self.slotRepeatAll)
		QObject.connect(self.repeatButton,PYSIGNAL('repeatOne'),self.slotRepeatOne)
		QToolTip.add(self.repeatButton,i18n("Play playlist once, repeat playlist, or repeat song"))
		# XXX DSM from settings
		self.repeatButton.setState('off')
		self.repeatButton.setFlat(True)
		QWhatsThis.add(self.repeatButton,i18n("This button changes the repeat behavior of the player.  An individual song or entire playlist can be set to repeat.  You can also use the commands from the <b>Edit</b> menu."))

	def buildLowerBar(self,container,containerLayout):
		#container=None
		lowerBar = QHBoxLayout()
		containerLayout.addLayout(lowerBar)
		self.buildLeftButtons(container,lowerBar)
		self.buildSummary(container,lowerBar)
		self.buildRightButtons(container,lowerBar)
	

	def buildLeftButtons(self,container,containerLayout):
		leftButtons = QHBoxLayout()
		containerLayout.addLayout(leftButtons)
		leftButtons.setSpacing(10)
		bSize = QSize(28,22)

		#
		# new simple playlist button
		#
		self.createPlaylistButton = QPushButton(QIconSet(QPixmap(art("buttonadd.png"))),"",container)
		self.createPlaylistButton.setFixedSize(bSize)
		leftButtons.addWidget(self.createPlaylistButton)
		QObject.connect(self.createPlaylistButton,SIGNAL("clicked()"),self.slotNewPlaylist)
		QToolTip.add(self.createPlaylistButton,i18n("Create a playlist"))
		QWhatsThis.add(self.createPlaylistButton,i18n("This button will create a new, empty, untitled playlist. You can also use the <b>New Playlist</b> command from the <b>File</b> menu."))
		'''
		#
		# show/hide artwork
		#
		iconoff = QIconSet(QPixmap(art("buttonartworkoff.png")))
		iconon = QIconSet(QPixmap(art("buttonartworkon.png")))
		self.showArtworkButton = MultiPushButton("",container)
		self.showArtworkButton.setFixedSize(bSize)
		self.showArtworkButton.addState('off',iconoff,PYSIGNAL('slotArtworkOn'))
		self.showArtworkButton.addState('on',iconon,PYSIGNAL('slotArtworkOff'))
		leftButtons.addWidget(self.showArtworkButton)
		QObject.connect(self.showArtworkButton,PYSIGNAL("slotArtworkOn"),self.slotToggleArtwork)
		QObject.connect(self.showArtworkButton,PYSIGNAL("slotArtworkOff"),self.slotToggleArtwork)
		QToolTip.add(self.showArtworkButton,i18n("Show or hide song artwork"))
		# XXX DSM from settings
		self.showArtworkButton.setState('off')
		QWhatsThis.add(self.showArtworkButton,i18n("This button toggles the visibility of the album artwork view.  You can also use the <b>Show/Hide Artwork</b> command from the <b>Edit</b> menu."))
		'''
	def buildRightButtons(self,container,containerLayout):
		rightButtons = QHBoxLayout()
		containerLayout.addLayout(rightButtons)
		rightButtons.setSpacing(10)
		bSize = QSize(28,22)

		#
		# show/hide equalizer
		#
		# this button opens the eq panel, but reflects the state of the eq
		#
		iconoff = QIconSet(QPixmap(art("buttoneqoff.png")))
		iconon = QIconSet(QPixmap(art("buttoneqon.png")))
		self.equalizerButton = MultiPushButton("",container)
		self.equalizerButton.setFixedSize(bSize)
		self.equalizerButton.addState('off',iconoff,PYSIGNAL('slotEqualizerOn'),'on')
		self.equalizerButton.addState('on',iconon,PYSIGNAL('slotEqualizerOff'),'off')
		rightButtons.addWidget(self.equalizerButton)
		QObject.connect(self.equalizerButton,PYSIGNAL("slotEqualizerOn"),self.slotEqualizer)
		QObject.connect(self.equalizerButton,PYSIGNAL("slotEqualizerOff"),self.slotEqualizer)
		QToolTip.add(self.equalizerButton,i18n("Open the Equalizer window"))
		# XXX DSM from settings
		self.equalizerButton.setState('off')
		QWhatsThis.add(self.equalizerButton,i18n("This button toggles the visibility of the Equalizer."))
		'''
		#
		# show/hide visualizer button
		#
		# this button starts the visualizer, but reflects the "full screen" setting
		#
		iconoff = QIconSet(QPixmap(art("buttonvisualizeroff.png")))
		iconon = QIconSet(QPixmap(art("buttonvisualizeron.png")))
		iconfull = QIconSet(QPixmap(art("buttonvisualizerfull.png")))
		self.visualizerButton = MultiPushButton("",container)
		self.visualizerButton.setFixedSize(bSize)
		self.visualizerButton.addState('off',iconoff,PYSIGNAL('slotVisualizerOn'))
		self.visualizerButton.addState('on',iconon,PYSIGNAL('slotVisualizerOff'))
		self.visualizerButton.addState('full',iconfull,PYSIGNAL('slotFullScreenVisualizer'))
		rightButtons.addWidget(self.visualizerButton)
		QObject.connect(self.visualizerButton,PYSIGNAL("slotVisualizerOn"),self.slotToggleVisualizer)
		QObject.connect(self.visualizerButton,PYSIGNAL("slotVisualizerOff"),self.slotToggleVisualizer)
		QObject.connect(self.visualizerButton,PYSIGNAL("slotFullScreenVisualizer"),self.slotToggleVisualizer)
		QToolTip.add(self.visualizerButton,i18n("Turn visual effects on or off"))
		# XXX DSM from settings (full vs other size)
		self.visualizerButton.setState('off')
		QWhatsThis.add(self.visualizerButton,i18n("This button toggles the visibility of the Visualizer.  You can also use the <b>Turn Visualizer On/Off</b> command from the <b>Controls</b> menu."))
		'''
		# Prefs  button
		#
		self.prefsButton = QPushButton(QIconSet(QPixmap(art("buttonprefs.png"))),"",container)
		self.prefsButton.setFixedSize(bSize)
		rightButtons.addWidget(self.prefsButton)
		QObject.connect(self.prefsButton,SIGNAL("clicked()"),self.slotPreferences)
		QToolTip.add(self.prefsButton,i18n("Adjust Preferences"))

		# Quit  button
		#
		self.quitButton = QPushButton(QIconSet(QPixmap(art("buttonquit.png"))),"",container)
		self.quitButton.setFixedSize(bSize)
		rightButtons.addWidget(self.quitButton)
		QObject.connect(self.quitButton,SIGNAL("clicked()"),self.slotQuit)
		QToolTip.add(self.quitButton,i18n("Quit 8traK"))

	def buildSummary(self,container,containerLayout):
		self.summary = Summary(container)
		self.summary.setAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
		self.summary.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed)
		containerLayout.addWidget(self.summary)
		QWhatsThis.add(self.summary,i18n("This view shows summary information about the currently listed tracks."))

	def buildMain(self,container,containerLayout):
		self.buildListViews(container,containerLayout)
		self.buildSearch(container,containerLayout)
	'''
	def buildVisualizer(self,container):
		self.visualizer = QWidget()
		self.visualizer.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
		self.visualizer.setPaletteBackgroundColor(QColor(0,0,0))
		container.addWidget(self.visualizer)
	'''
	def buildListViews(self,container,containerLayout):
		self.listViews = QSplitter(container,"selector")
		containerLayout.addWidget(self.listViews)
		self.listViews.setOpaqueResize(True)
		self.buildSourcesAndArtwork(self.listViews)
		self.buildTrackViews(self.listViews)
		#if self.settings.has_key('Main Window Split'):
		#	self.listViews.setSizes(eval(self.settings['Main Window Split']))

	def buildTrackViews(self,container):
		#self.trackViewAndSearchContainer = QWidget(container,"trackviewandsearchcontainer")
		#self.trackViewAndSearchLayout = QVBoxLayout(self.trackViewAndSearchContainer)
		#self.trackViewContainer = QWidget(self.trackViewAndSearchContainer,"trackviewcontainer")
		#self.trackViewAndSearchContainer.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
		self.trackViewContainer = QWidget(container,"trackviewcontainer")
		self.trackViewLayout = QVBoxLayout(self.trackViewContainer)
		self.trackViewContainer.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
		self.trackView = None
		self.trackViewType = ''
		QObject.connect(self.sources,PYSIGNAL("selectLibrary"),self.selectLibrary)
		QObject.connect(self.sources,PYSIGNAL("selectPlaylist"),self.selectPlaylist)
		QObject.connect(self.sources,PYSIGNAL("selectAudioCD"),self.selectAudioCD)
		QObject.connect(self.sources,PYSIGNAL("selectTrash"),self.selectTrash)
		QObject.connect(self.sources,PYSIGNAL("selectRadio"),self.selectRadio)
		#QObject.connect(self.sources,PYSIGNAL("selectPodPlaylist"),self.selectPodPlaylist)
		QObject.connect(self.sources,PYSIGNAL("selectSlimp3"),self.selectSlimp3)
		QObject.connect(self.sources,PYSIGNAL("selectSharedPlaylist"),self.selectSharedPlaylist)
		QObject.connect(self.sources,PYSIGNAL("selectEncoder"),self.selectEncoder)

	def buildGetInfoPanel(self,track,container):
		self.getInfoPanel=getInfoPanel(track,self.trackViewContainer)
		self.trackViewLayout.addWidget(self.getInfoPanel)
		pass
	
	def killCurrentTrackView(self):
		if self.trackView:
			if self.trackViewType=='library':
				self.libraryViewRef = self.trackView
				self.libraryViewRef.reparent(self,0,QPoint(0,0),False)
				self.detachSearch(self.libraryViewRef)
				self.trackView = None
			else:
				self.summary.detachFrom(self.trackView)
				self.trackView.aboutToDie()
				self.trackView.deleteLater()
				self.trackView = None
			self.trackViewType = ''

	def selectPlaylist(self,playlist):
		if self.trackViewType!='playlist':
			self.killCurrentTrackView()
			self.trackView = self.buildPlaylistView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'playlist'
			self.functionButton.setState('burnon')
			self.updateMenusAndControls()
		self.trackView.setPlaylist(playlist)

	def selectLibrary(self):
		if self.trackViewType!='library':
			self.killCurrentTrackView()
			if self.libraryViewRef!=None:
				self.trackView = self.libraryViewRef
				self.trackView.reparent(self.trackViewContainer,0,QPoint(0,0),True)
				self.trackViewLayout.addWidget(self.trackView)
				self.summary.attachTo(self.trackView)
				self.attachSearch(self.trackView)
			else:
				self.trackView = self.buildBrowserAndLibrary(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()


			self.trackViewType='library'
			self.functionButton.setState('browse')
			self.updateMenusAndControls()
		
	
	def selectAudioCD(self,library):
		if 1: # self.trackViewType!='audiocd': # XXX DSM always build
			self.killCurrentTrackView()
			self.trackView = self.buildAudioCDView(self.trackViewContainer,self.trackViewLayout,library)
			self.trackView.show()
			self.trackViewType = 'audiocd'
			self.functionButton.setState('import')
		self.disableArt()

	def selectPodPlaylist(self,playlist):
		if self.trackViewType!='pod':
			self.killCurrentTrackView()
			self.trackView = self.buildPodView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'pod'
			#/self.functionButton.setState('import')
			self.updateMenusAndControls()
		self.trackView.setPlaylist(playlist)
		self.disableArt()

	def selectTrash(self):
		if self.trackViewType!='trash':
			self.killCurrentTrackView()
			self.trackView = self.buildTrashView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'trash'
			self.functionButton.setState('browse')
			self.updateMenusAndControls()
		library = Library.mainLibrary()
		self.trackView.setPlaylist(library.playlistWithName('Trash'))
		self.disableArt()
	
	def selectRadio(self):
		if self.trackViewType!='radio':
			self.killCurrentTrackView()
			self.trackView = self.buildRadioView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'radio'
			self.functionButton.setState('refresh')
			self.updateMenusAndControls()
			self.disableArt()
	
	def selectSlimp3(self,name,type,address,port):
		self.killCurrentTrackView()
		self.trackView = self.buildSlimp3View(self.trackViewContainer,self.trackViewLayout,name,type,address,port)
		self.trackView.show()
		self.trackViewType = 'slimp3'
		self.functionButton.setState("browse")
		self.updateMenusAndControls()
		self.disableArt()
	
	def selectSharedPlaylist(self,playlist):
		if self.trackViewType!='shared':
			self.killCurrentTrackView()
			self.trackView = self.buildSharedPlaylistView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'shared'
			self.functionButton.setState('sync')
			self.updateMenusAndControls()
		self.trackView.setPlaylist(playlist)
		self.disableArt()

	def selectEncoder(self):
		if self.trackViewType!='encoder':
			self.killCurrentTrackView()
			self.trackView = self.buildEncoderView(self.trackViewContainer,self.trackViewLayout)
			self.trackView.show()
			self.trackViewType = 'encoder'
			self.functionButton.setState('burnon')
			self.updateMenusAndControls()
		#self.trackView.setPlaylist(playlist)

	def buildSourcesAndArtwork(self,container):
		self.sourcesAndArtwork = QVBox(container)
		self.sourcesAndArtwork.setSpacing(3)
		self.buildSourceView(self.sourcesAndArtwork)
		self.buildArtworkView(self.sourcesAndArtwork)

	def buildSourceView(self,container):
		self.sources = SourceView(container,self)
		QWhatsThis.add(self.sources,i18n("This view shows the list of sources of music that 8trak manages."))

	def buildArtworkView(self,container):
		self.artworkView = QFrame(container)
		#
		# XXX DSM frame not showing up..?
		#
		self.artworkView.setFrameShape(QFrame.Panel)
		self.artworkView.setFrameShadow(QFrame.Sunken)
		self.artworkView.setLineWidth(2)
		#
		layout = QVBoxLayout(self.artworkView)
		header = QHeader(self.artworkView)
		layout.addWidget(header)
		header.addLabel(i18n("Selected Song"))
		header.setOrientation(Qt.Horizontal)
		header.setStretchEnabled(True,0)
		self.artwork = ArtworkView(self.artworkView,"artwork",container)
		layout.addWidget(self.artwork)
		#
		# XXX DSM check settings
		#
		self.artworkView.hide()
		QWhatsThis.add(self.artworkView,i18n("This view shows the available artwork for the currently selected track."))

	def attachSearch(self,view):
		QObject.connect(self.search,PYSIGNAL('setSearchType'),view.setSearchType)
		QObject.connect(self.search,PYSIGNAL('setSearchText'),view.setSearchText)
	
	def detachSearch(self,view):
		QObject.disconnect(self.search,PYSIGNAL('setSearchType'),view.setSearchType)
		QObject.disconnect(self.search,PYSIGNAL('setSearchText'),view.setSearchText)

	def attachMenuUpdates(self,view):
		QObject.connect(view,PYSIGNAL('selectionChanged'),self.updateMenusAndControls)

	def detachMenuUpdates(self,view):
		QObject.disconnect(view,PYSIGNAL('selectionChanged'),self.updateMenusAndControls)
	
	def attachArtwork(self,view):
		QObject.connect(view,PYSIGNAL('selectedItem'),self.artwork.artCap)

	def detachArtwork(self,view):
		QObject.disconnect(view,PYSIGNAL('selectedItem'),self.artwork.artCap)
	
	def buildBrowserAndLibrary(self,container,containerLayout):
		view = MainLibraryView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.attachArtwork(view)
		self.summary.attachTo(view)
		return view

	def buildPlaylistView(self,container,containerLayout):
		view = PlaylistView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.attachArtwork(view)
		self.summary.attachTo(view)
		return view

	def buildAudioCDView(self,container,containerLayout,library):
		view = AudioCDView(container,library)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view
	'''
	def buildDellView(self,container,containerLayout):
		view = LDellTrackView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view
	def buildPodView(self,container,containerLayout):
		view = PodTrackView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view
	'''
	def buildTrashView(self,container,containerLayout):
		view = TrashView(container)
		containerLayout.addWidget(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view

	def buildSharedPlaylistView(self,container,containerLayout):
		view = LRemotePlaylistView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view

	def buildRadioView(self,container,containerLayout):
		#view = LRadioView(container)
		view = StationsView(self,container)
		containerLayout.addWidget(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view

	def buildSlimp3View(self,container,containerLayout,name,type,address,port):
		view = Slimp3View(self,container,name,type,address,port)
		containerLayout.addWidget(view)
		self.summary.attachTo(view)
		return view

	def buildEncoderView(self,container,containerLayout):
		view = EncoderView(container)
		containerLayout.addWidget(view)
		self.attachSearch(view)
		self.attachMenuUpdates(view)
		self.summary.attachTo(view)
		return view

	def initSignals(self):
		QObject.connect(Encoder.singleton(),PYSIGNAL('status'),self.encodedTrack)
		QObject.connect(Importer.singleton(),PYSIGNAL('status'),self.importedTrack)
		#QObject.connect(MusicDellManager.singleton(),PYSIGNAL('status'),self.importedDellTrack)
		#QObject.connect(MusicPodManager.singleton(),PYSIGNAL('status'),self.importedPodTrack)
		QObject.connect(CDLibraries.singleton(),PYSIGNAL('cdMounted'),self.cdMounted)

	def encodedTrack(self,status):
		library = Library.mainLibrary()
		if status['Source']=='Encoder':
			if status['Status']=='EndTrack':
				if not status.get('Interrupted',False):
					filePath = status['FilePath']
					track = library.importFile(filePath,True)
					try:
						protoTrack = status['Track']
						tags = protoTrack.loadTagsInto(None)
						#print "copying",tags
						track.loadTagsFrom(tags)
					except: pass
					try: os.remove(filePath)
					except: pass
					if track:
						track.dateEncoded = time.gmtime(time.time())
						track.dateModified = track.dateEncoded
					library.markDirty()

	def importedTrack(self,status):
		if status['Status']=='End':
			library = Library.mainLibrary()
			library.markDirty()
	'''
	def importedDellTrack(self,status):
		library = Library.mainLibrary()
		if status['Status']=='Downloaded Track':
			filePath = status['filePath']
			track = None
			if not status.get('Interrupted',False):
				playlists = status['Playlist']
				if playlists: playlists = [playlists]
				track = library.importFile(filePath,True,playlists)
			#print "imported, now killing",filePath
			try: os.remove(filePath)
			except: pass
		elif status['Status']=='End':
			library.markDirty()

	def importedPodTrack(self,status):
		library = Library.mainLibrary()
		if status['Status']=='Downloaded Track':
			filePath = status['filePath']
			track = None
			if not status.get('Interrupted',False):
				playlists = status['Playlist']
				if playlists: playlists = [playlists]
				track = library.importFile(filePath,True,playlists)
			#print "imported, now killing",filePath
			try: os.remove(filePath)
			except: pass
		elif status['Status']=='End':
			library.markDirty()
	
	def exportedDellTrack(self,status):
		if status['Status']=='End':
			DellLibrary.mount()
	
	def exportedPodTrack(self,status):
		if status['Status']=='End':
			PodLibrary.mount()
	'''
	def cdMounted(self,library,firstTime = False):
		#print "CD Mounted!"
		action = self.settings.get('CD Insertion Action','show')
		if not firstTime:
			if action=='import' or action=='importAndEject':
				tracks = library.tracks()
				tracks = [tracks[trackKey] for trackKey in tracks.keys()]
				CD.Ripper.singleton().ripTracks(tracks)
			elif action=='play':
				track = library.trackWithTrackNum(1)
				if track:
					track.play()
